<?php
/**
 * Created by PhpStorm.
 * User: aeball
 * Date: 2017/4/28
 * Time: 16:01
 */

namespace app\index\controller;

use think\Config;
use think\Controller;
use think\Session;
use think\Db;
use app\common\model\Collection;
use app\common\model\User;

/*
 * 前台登录
 * */
class Login  extends Controller
{

    public function index(){
        return $this->fetch();
    }

    /*
     * 登录验证 账号登录
     * */
    public function login(){
        if ($this->request->isPost()) {
            // $data            = $this->request->only(['username', 'password', 'verify']);
            $data            = $this->request->only(['username', 'password']);
            $validate_result = $this->validate($data, 'Login');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $where['username|mobile|email'] = $data['username'];
                // 密码加入盐值混淆判断
                $where['password'] = md5($data['password'] . Config::get('salt'));


                $admin_user = Db::name('user')->field('id,username,status,create_time,open_time,header_url,sex,mobile,integral,open_vip')->where($where)->find();



                if (!empty($admin_user)) {
                    if ($admin_user['status'] != 1) {
                        $this->error('当前用户已禁用');
                    } else {
                            //有效期
                            $create_time = strtotime($admin_user['create_time']);
                            if($admin_user['open_time'] > 0){
                                $open_time = $create_time + $admin_user['open_time'] * 3600;
                                if(time() > $open_time){
                                    Db::name('user')->where(['id'=>$admin_user['id']])->update(['status'=>0]);
                                    $this->error('当前用户已失效');
                                }
                            }
                        Session::set('index_user', $admin_user);
                        Session::set('index_id', $admin_user['id']);
                        Session::set('index_name', $admin_user['username']);
                        Db::name('user')->update(
                            [
                                'last_login_time' => date('Y-m-d H:i:s', time()),
                                'last_login_ip'   => $this->request->ip(),
                                'id'              => $admin_user['id']
                            ]
                        );
                        return json(['status'=>1,'msg'=>'登录成功']);
                    }
                } else {
                    return json(['status'=>0,'msg'=>'用户名或密码错误']);
                }
            }
        }

    }

    public function wechatLogin(){
        $url = "https://open.weixin.qq.com/connect/qrconnect?appid=wxf72745ea140eba85&redirect_uri=https%3a%2f%2fdsj.gzshangning.com/index/login/getcode&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        $this->redirect($url);
    }


    /**
     * 
        { 
            "access_token":"ACCESS_TOKEN", 
            "expires_in":7200, 
            "refresh_token":"REFRESH_TOKEN",
            "openid":"OPENID", 
            "scope":"SCOPE",
            "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
        }
    */
    public function getcode($code){
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxf72745ea140eba85&secret=0aa78e8e7936c8c3bdf54590d5546acd&code={$code}&grant_type=authorization_code";
        $result = httpRequest($url);
        if(isset($result['errcode'])){
            return json(['status' => -1 , 'error' => $result['errmsg']]);
        }
        $data = json_decode($result,true);

        //查询该账号是否存在
        $user_data = Db::name('user')->where('openid',$data['openid'])->find();
        if($user_data){
            $collection_model = new Collection;
            $collection = $collection_model->getCollectionlist($user_data['id']);
            $user_data['collection'] = $collection;
            Session::set('index_user', $user_data);
            Session::set('index_id', $user_data['id']);
            Session::set('index_name', $user_data['nickname']);
            Db::name('user')->where('openid',$user_data['openid'])->update(
                [
                    'last_login_time' => date('Y-m-d H:i:s', time()),
                    'last_login_ip'   => $this->request->ip(),
                ]
            );
            $this->redirect('/index/index/index');
        }else{
            //注册
            $user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN";
            $user_info_data = httpRequest($user_info_url);
            if($user_info_data){
                $user_info = json_decode($user_info_data,true);
                $user_info['header_url'] = $user_info['headimgurl'];
                $user_info['origin'] = 'weixin';
                $user_info['integral'] = 0;
                $user_info['create_time'] = date('Y-m-d H:i:s');
                $userip = $this->request->ip();
                if($userip){
                    $url = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$userip;
                    $addrJson = httpRequest($url);
                    $addr = json_decode($addrJson,true);
                    if($addr['code'] == 0){
                        $user_info['province'] = $addr['data']['region'];
                        $user_info['city'] = $addr['data']['city'];
                    }
                }
                $res = Db::name('user')->strict(false)->insertGetId($user_info);
                if($res){
                    //注册成功
                    Session::set('index_user', $user_info);
                    Session::set('index_id', $res);
                    Session::set('index_name', $user_info['nickname']);
                    $this->redirect('/index/index/index');
                }else{
                    $this->redirect('/index/index/index');
                }
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Session::delete('index_id');
        Session::delete('index_name');
        $this->success('退出成功', 'index/index/index');
    }






}